<?php

namespace App\Services;

use App\Models\NewsModel;

class NewsService extends BaseService {

    public function getList($params) {
        $news_type = data_get($params, 'news_type', 0);
        $img = data_get($params, 'img', null);
        $home = data_get($params, 'home', null);
        $page = data_get($params, 'page', 0);
        $limit = data_get($params, 'limit', 20);

        $query = NewsModel::query();
        $query->when($news_type, function($query)use($news_type){
            $query->where("news_type", $news_type);
        });
        $query->when($img, function($query)use($img){
           $query->whereNotNull("images");
        });
        $query->orderBy('id', 'desc');
        $res = $query->paginate($limit, NewsModel::$columns, 'page', $page)->toArray();
        if ($home == 1){
            return $res;
        }else {
            return [
                'page' => $res['total'],
                'list' => $res['data']
            ];
        }
    }

    public function info($info_id) {
        $res = NewsModel::query()->where("id", $info_id)->first();
        return $res ? $res->toArray() : [];
    }

    public function up_down($info_id, $type="up"){
        if ($type == "up"){
            $res = NewsModel::query()->where("id", "<",  $info_id)->first();
        }elseif ($type == "down"){
            $res = NewsModel::query()->where("id", ">", $info_id)->first();
        }

        return $res ? $res->toArray() : [];
    }

    public function save($params, $info_id=0){
        if (empty($info_id)){
            $news_model = new NewsModel();
        }else{
            $news_model = NewsModel::find($info_id);
        }
        $news_model->news_type = data_get($params, 'news_type', 0);
        $news_model->title = data_get($params, 'title', '');
        $news_model->content = data_get($params, 'content', '');
        $news_model->images = data_get($params, 'images', '');
        $news_model->save();
        if (empty($news_model->id)) {
            return false;
        }
        return true;
    }

    public function delete($info_id) {
        return NewsModel::query()->where("id", $info_id)->delete();
    }
}